import { writeFileXLSX, utils as XLSXUtil, WritingOptions } from 'xlsx';
import * as Lodash from 'lodash';

/**
 * 从地址码获取省市区编码（没用，已通过后端接口调整）
 * @param code 编码
 * @param areas 地址列表
 * @returns
 */
export function getAddressCodes(code: string, areas: any[]) {
  const codes = {
    provinceCode: '',
    cityCode: '',
    districtCode: '',
  };
  for (let i = 0; i < areas.length; ) {
    const area = areas[i];
    const pCode = area.value;
    if (pCode === code) {
      codes.provinceCode = pCode;
      return codes;
    }
    const pChildren: any[] = area.children;
    if (pChildren) {
      for (let j = 0; j < pChildren.length; j += 1) {
        const city = pChildren[j];
        const cCode = city.value;
        if (cCode === code) {
          codes.provinceCode = pCode;
          codes.cityCode = cCode;
          return codes;
        }
        const cChildren: any[] = city.children;
        if (cChildren) {
          for (let k = 0; k < cChildren.length; k += 1) {
            const district = cChildren[k];
            const dCode = district.value;
            if (dCode === code) {
              codes.provinceCode = pCode;
              codes.cityCode = cCode;
              codes.districtCode = dCode;
              return codes;
            }
          }
        }
      }
    }
  }
  return codes;
}

/**
 * json 数据结构转换
 * @param dataObjs
 * @param key
 * @returns
 */
export function getDataMapFromObjects(dataObjs: any[], key: string) {
  const output: any = {};
  for (let i = 0; i < dataObjs.length; i += 1) {
    const dataObj = dataObjs[i];
    if (dataObj[key]) {
      output[dataObj[key]] = dataObj;
    }
  }
  return output;
}

/**
 * 获取带有时间的文件名
 * @param prefix
 * @param suffix
 * @returns
 */
export function getDatetimeFilename(prefix = '', suffix = '') {
  const dateObj = new Date();
  let filename = `${prefix}${dateObj.getFullYear()}年${
    dateObj.getMonth() + 1
  }月${dateObj.getDate()}日`;
  filename += ` ${dateObj.getHours()}时${dateObj.getMinutes()}分${dateObj.getSeconds()}秒${suffix}`;
  return filename;
}

class XlsxUtil {
  /**
   *
   * @param filename
   * @param data
   */
  public static writeDownload(filename: string, data: any[]) {
    if (!data || data.length === 0) {
      return false;
    }
    const options: WritingOptions = {
      type: 'file',
      bookType: 'xlsx',
      ignoreEC: true,
    };
    const workbook = {
      Sheets: { sheet1: XLSXUtil.json_to_sheet(data) },
      SheetNames: ['sheet1'],
    };
    try {
      return writeFileXLSX(workbook, filename, options);
    } catch (error) {
      return false;
    }
  }
}

export { XlsxUtil };
